import { DeviceEventEmitter } from 'react-native';
import JPushModule from 'jpush-react-native';
import { getActiveRouteName } from '../router';

export const setAlias = (alias) => new Promise(resolve => {
  JPushModule.setAlias(alias, () => {
    resolve(true);
  }, () => {
    resolve(false);
  });
});

export const setTags = (tag) => new Promise(resolve => {
  JPushModule.setTags([tag], () => {
    resolve(true);
  }, () => {
    resolve(false);
  });
});

export const getRegistrationID = () => new Promise(resolve => {
  JPushModule.getRegistrationID((registrationId) => {
    resolve(registrationId);
  }, () => {
    resolve(false);
  });
});

// 添加极光推送消息处理事件的绑定
export const addJPushListener = () => {
  JPushModule.notifyJSDidLoad((resultCode) => { // 要处理消息事件，必须先执行该方法
    if (resultCode === 0) {
      // 返回0表示可以绑定消息处理事件
      // alert('1');
    }
  });
  JPushModule.addReceiveNotificationListener((msg) => {
    console.log(msg);
    DeviceEventEmitter.emit('refreshBadgeEvent');
  });
  JPushModule.addReceiveCustomMsgListener((msg) => {
    // 处理自定义消息
    console.log(msg);
  });
  JPushModule.addReceiveOpenNotificationListener((map) => {
    // 处理消息栏点击事件
    console.log(map);
    const routerName = getActiveRouteName(global.navigation.state);
    if (routerName !== 'PushList') {
      global.navigation.navigate({ routeName: 'PushList' });
    }
  });
};

// 取消极光推送消息处理事件的绑定
export const rmJPushListener = () => {
  JPushModule.removeReceiveCustomMsgListener();
  JPushModule.removeReceiveNotificationListener();
  JPushModule.removeReceiveOpenNotificationListener();
};
